package JianZhiOffer;

import JianZhiOffer.entity.ListNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 *
 * 链表倒序输出数组
 *
 * 辅助栈
 * 递归
 * 链表反转
 */
public class Solution06 {

    public int[] reversePrint1(ListNode head) {
        if (head == null) return new int[]{};
        Stack<ListNode> stack = new Stack<>();
        stack.push(head);
        ListNode currentNode = head.next;
        while (currentNode != null) {
            stack.push(currentNode);
            currentNode = currentNode.next;
        }

        int[] ints = new int[stack.size()];
        int index = 0;
        while (!stack.empty()) {
            ints[index] = stack.pop().val;
            index++;
        }
        return ints;
    }


    List<Integer> list = new ArrayList<>();

    public int[] reversePrint2(ListNode head) {
        if (head == null) return new int[]{};
        addNode(head);
        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ints[i] = list.get(i);
        }
        return ints;
    }

    void addNode(ListNode node) {
        if (node == null) return;
        addNode(node.next);
        list.add(node.val);
        return;
    }

    public int[] reversePrint3(ListNode head) {
        if (head == null) return new int[]{};
        ListNode prev = null;
        ListNode current = head;
        ListNode next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        List<Integer> list = new ArrayList<>();
        while (prev != null){
            list.add(prev.val);
            prev = prev.next;
        }

        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ints[i] = list.get(i);
        }
        return ints;
    }

    public static void main(String[] args) {


    }
}
